from langchain.text_splitter import CharacterTextSplitter,MarkdownTextSplitter,RecursiveCharacterTextSplitter
# from langchain.document_loaders import UnstructuredFileLoader,UnstructuredMarkdownLoader,UnstructuredWordDocumentLoader
import os
from fastapi import APIRouter, Query, UploadFile, File,Form,Body,Request
from xingchen import Configuration, CharacterPermissionConfig,ApiClient, ChatApiSub, ChatReqParams,CharacterUpdateDTO, CharacterKey, Message, UserProfile, ModelParameters,ChatContext,CharacterCreateDTO,CharacterApiSub
import time

from typing import Optional
from pydantic import BaseModel
from embeddingDB import pgDB
from typing import Dict, Any
 
router = APIRouter(
    prefix= "/user",
    tags= ["userRouter"],
    responses= {404: {"description": "Not found path knowledge"}}
)

class userMessage(BaseModel):
    user_id: Optional[str] = ""
    nickname: Optional[str] = ""
    user_id: Optional[str] = ""
    content: Optional[str] = ""

from fastapi.responses import StreamingResponse
# @router.post("/tts")
# async def tts(msg:userMessage):
#     return ""
    # return StreamingResponse(generate_text_from_xingchen(msg), media_type="text/plain")
# test_chat_async()
# test_chat_sync()

# work_dir = "."lm-qbcQwj0A9CKMEBu4YkVe6Q==

from datetime import datetime
class User(BaseModel):
    id:Optional[int] = 0
    username: Optional[str] = ""
    password: Optional[str] = ""
    nickname: Optional[str] = "尚未被主人起名的小新"
    introduction: Optional[str] = "主人太懒了，还没介绍这位小新同学"
    create_time: Optional[datetime] = ""
    update_time: Optional[datetime] = ""
    device_device_id:Optional[str] = ""
    
def getUserInfoByUserId(userId):
    
    db = pgDB()
    sql = '''
SELECT 
    u.username,
    u.id,
    u.password,
    u.nickname,
    u.update_time,
    u.introduction,
    u.create_time,
    CASE WHEN COUNT(d.id) > 0 THEN json_agg(
        json_build_object(
            'id', d.id,
            'update_time', d.update_time,
            'user_id', ud.user_id,
            'device_device_id', d.device_id,
            'create_time', d.create_time,
            'name', d.name,
            'device_id', d.device_id,
            'introduction', d.introduction,
            'mac', d.mac,
            'location', d.location,
            'login_time', d.login_time,
            'role_agent', COALESCE(
                json_build_object(
                    'name', ra.name,
                    'id', ra.id,
                    'character_id', ra.character_id,
                    'create_time', ra.create_time,
                    'update_time', ra.update_time,
                    'introduction', ra.introduction,
                    'basic_information', ra.basic_information,
                    'opening_line', ra.opening_line,
                    'traits', ra.traits,
                    'chat_example', ra.chat_example,
                    'type', ra.type,
                    'chat_objective', ra.chat_objective,
                    'sound', ra.sound
                ), '{}'
            ),
            'memory', d.memory
        )
    ) ELSE '[]' END AS device
FROM 
    public."user" u
LEFT JOIN 
    public."user_device" ud ON u.id = ud.user_id
LEFT JOIN 
    public."device" d ON ud.device_device_id = d.device_id
LEFT JOIN 
    public."role_agent" ra ON d.role_agent_id = ra.id
WHERE 
    u.id = '{}'
GROUP BY 
    u.username, u.id, u.password, u.nickname, u.update_time, u.introduction, u.create_time;




    '''.format("{}",userId)
    # print(sql)
    data_device = db.select(sql)[0]
    # data_user.update({"device":data_device})
    
    db.close()
    return data_device


@router.post("/register")
def register(params:User):
    rs = {"code":200,"msg":"创建成功","data":{}}
    sql = '''
    INSERT INTO "user"(username,nickname,introduction,"password")
    VALUES('{}','{}','{}','{}')
    '''.format(params.username,params.nickname,params.introduction,params.password)
    db = pgDB()
    db.modify(sql)
    db.close()
    rs["data"] = {}
    return rs


@router.post("/registerUserDevice")
def registerUserDevice(params:User):
    print("registerUserDevice:",params)
    db = pgDB()
    rs = {"code":200,"msg":"绑定设备成功","data":{}}
    sql = '''
    DELETE FROM "user_device" WHERE device_device_id = '{}'
    '''.format(params.device_device_id)
    db.modify(sql)
    
    sql = '''
    INSERT INTO "user_device"(user_id,device_device_id)
    VALUES('{}','{}')
    '''.format(params.id,params.device_device_id)
    db.modify(sql)
    
    db.close()
    rs["data"] = {}
    return rs

@router.post("/update")
def update(params:User):
    rs = {"code":200,"msg":"更新成功","data":{}}
    # name = params.name
    print(params)
    # 角色管理准备部分已省略

    
    sql = '''
    UPDATE "user"
    SET nickname='{}',introduction='{}'
    WHERE id='{}'
    
    '''.format(params.nickname,params.introduction,params.id)
    db = pgDB()
    print(sql)
    db.modify(sql)
    db.close()
    
    
    # k = embeddingDB.VectorDB()
    # k.getCollection(title)
    # print()
    rs["data"] = {}
    return rs

    
@router.post("/getUserList")
def getUserList(params:User):
    rs = {"code":200,"msg":"创建成功","data":{}}
    # title = params.title
    # print(params)
    
    sql = '''
    SELECT *
    FROM "user"
    '''
    db = pgDB()
    data = db.select(sql)
    db.close()
    
    # data = [ convert_keys_to_camel(User(**d).dict()) for d in data]
    # data = data.dict()  # 将 Pydantic 模型转换为字典
    # data = convert_keys_to_camel(data)  # 将字典键转换为驼峰命名
    
    rs["data"] = data
    print(">>",rs["data"])
    return rs
    
@router.post("/delete")
def delete(params:User):
    rs = {"code":200,"msg":"删除成功","data":{}}
    print(params)
    sql = '''
    DELETE FROM "user" 
    WHERE id = '{}'
    '''.format(params.id)
    db = pgDB()
    data = db.modify(sql)
    rs["data"] = {}
    db.close()
    
    # k.delUser(params.title)
    
    return rs
    
@router.post("/getUserInfo")
def getUserInfo(params:User):
    rs = {"code":200,"msg":"查询成功","data":{}}
    # title = params.title
    # print(params)
    data = getUserInfoByUserId(params.id)
    rs["data"] = data
    return rs
    
    
@router.post("/login")
def login(params:User):
    rs = {"code":200,"msg":"查询成功","data":{}}
    # title = params.title
    # print(params)
    sql = '''
    SELECT * FROM "user"
    WHERE username = '{}' and "password" = '{}'
    '''.format(params.username,params.password)
    # data = getUserInfoByUserId(params.id)
    db = pgDB()
    data = db.select(sql)
    if data is None or len(data)==0:
        rs["code"]=500
        rs["msg"]='登陆失败'
        rs["data"] = {}
    else:
        rs["data"] = data = getUserInfoByUserId(data[0]["id"])
    return rs
    
